﻿using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.ComponentModel;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Chromium;
using System.Reflection;

namespace SeleiumLoginGetHttp.qita
{
    internal class qitatxt
    {
        //seleium
        public static JObject PerformLoginAndCaptureNetworkInfo(string loginButtonXPath, string usernameXPath, string passwordXPath, string username, string password, string websiteUrl, string panduan, string panxpath, string leibie, string panduanzi, string zixpath, string zizhanghu, List<string> chaxun, bool showBrowser)
        {
            // 创建浏览器驱动
            using (var driver = CreateWebDriver(showBrowser))
            {
                // 导航到目标网站
                driver.Navigate().GoToUrl(websiteUrl);
                System.Threading.Thread.Sleep(4000);

                try
                {
                    // 判断是否需要先点击
                    if (panduan == "xuyao")
                    {
                        // 需要点击的xpath
                        var xuxpath = driver.FindElement(By.XPath(panxpath));
                        System.Threading.Thread.Sleep(2000);
                        // 点击登录按钮
                        xuxpath.Click();
                    }

                    // 判断是否有子账户
                    if (panduanzi == "shi01")
                    {
                        // 需要点击的xpath
                        var xuxpath01 = driver.FindElement(By.XPath(zixpath));
                        System.Threading.Thread.Sleep(2000);
                        // 输入用户名和密码
                        xuxpath01.SendKeys(zizhanghu);
                        System.Threading.Thread.Sleep(1000);
                    }

                    // 找到用户名和密码输入框，以及登录按钮
                    var usernameInput = driver.FindElement(By.XPath(usernameXPath)); // 使用传入的用户名输入框XPath
                    var passwordInput = driver.FindElement(By.XPath(passwordXPath)); // 使用传入的密码输入框XPath
                    var loginButton = driver.FindElement(By.XPath(loginButtonXPath)); // 查找登录按钮元素
                    System.Threading.Thread.Sleep(2000);

                    // 输入用户名和密码
                    usernameInput.SendKeys(username);
                    System.Threading.Thread.Sleep(1000);
                    passwordInput.SendKeys(password);
                    System.Threading.Thread.Sleep(1000);

                    // 点击登录按钮
                    loginButton.Click();
                    System.Threading.Thread.Sleep(3000);
                }
                catch (NoSuchElementException ex)
                {
                    // 处理找不到元素的情况
                    return JObject.Parse($"{{\"Error\": \"找到不元素XPath: {ex.Message}\"}}");
                }

                // 等待一段时间，以确保登录完成（你也可以使用显式等待）
                System.Threading.Thread.Sleep(5000);

                // 获取网络日志（请求和响应）
                var logs = driver.Manage().Logs.GetLog("performance");

                if (leibie == "quanbu")
                {
                    // 保存网络信息
                    JObject networkInfo = new JObject();
                    int count = 0;
                    foreach (var log in logs)
                    {
                        // 并将长度大于等于 300 且小于 5000 的日志消息添加到 networkInfo 列表中
                        string network = log.Message;
                        if (network.Length >= 300 && network.Length < 5000)
                        {
                            networkInfo.Add(new JProperty($"{count}", JObject.Parse(network)));
                            count++;
                        }
                    }

                    // 返回网络信息
                    return networkInfo;
                }
                else if (leibie == "qingqiu")
                {
                    JObject result = new JObject();

                    foreach (string keyword in chaxun)
                    {
                        // 将请求内容关键字的值添加到结果中
                        JObject value = FindVariableValue(logs, keyword, true);
                        if (value != null)
                        {
                            result[keyword] = value;
                        }
                        else
                        {
                            throw new Exception($"无法找到 {keyword} 请求内容关键字的值");
                        }
                    }

                    // 返回结果
                    return result;
                }
                else if (leibie == "xiangying")
                {
                    JObject result = new JObject();

                    foreach (string keyword in chaxun)
                    {
                        // 将响应内容添加到结果中
                        JObject value = FindVariableValue(logs, keyword, false);
                        if (value != null)
                        {
                            result[keyword] = value;
                        }
                        else
                        {
                            throw new Exception($"无法找到 {keyword} 响应内容");
                        }
                    }

                    // 返回结果
                    return result;
                }
                else
                {
                    throw new ArgumentException("leibie参数错误");
                }
            }
        }


        public static IWebDriver CreateWebDriver(bool showBrowser)
        {
            // 根据操作系统类型选择浏览器驱动
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // 获取公共文档路径 C:\Users\Public\Documents
                //string publicDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);

                // 拼接路径，确保没有额外的目录分隔符
                // string chromeDriverPath = Path.Combine(publicDocumentsPath, "ForguncyPluginv9", "唐哥插件合集-9_0_4_0");
                

                string fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Resources", "chromedriver.exe");

                // 设置工作路径，同时添加目录分隔符
                //string chromeDriverPath1 = Path.Combine(chromeDriverPath, "chromedriver.exe");
                string chromeDriverPath1 = Path.Combine(fileName);

                // Windows系统，
                var options = new ChromeOptions();

                if (!showBrowser)
                {
                    // 无头模式，可视化界面不显示
                    options.AddArguments("--headless");
                }

                //开启网络日志功能
                options.SetLoggingPreference("performance", OpenQA.Selenium.LogLevel.Info);
                options.PerformanceLoggingPreferences = new ChromiumPerformanceLoggingPreferences()
                {
                    IsCollectingNetworkEvents = true
                };
                // 设置路径并添加浏览器配置环境
                var chromeDriver = new ChromeDriver(chromeDriverPath1, options);

                // 设置浏览器全屏显示
                chromeDriver.Manage().Window.Maximize();

                return CreateDriver(chromeDriver);

            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {

                // Linux系统，使用Chrome浏览器
                var options = new ChromeOptions();
                if (!showBrowser)
                {
                    // 无头模式，可视化界面不显示
                    options.AddArguments("--headless");
                }
                //开启网络日志功能
                options.SetLoggingPreference("performance", OpenQA.Selenium.LogLevel.Info);
                options.PerformanceLoggingPreferences = new ChromiumPerformanceLoggingPreferences()
                {
                    IsCollectingNetworkEvents = true
                };
                // 取当前插件的路径下Resources的程序文件
                string fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Resources", "chromedriver");

                // 设置工作路径，同时添加目录分隔符
                //string chromeDriverPath1 = Path.Combine(chromeDriverPath, "chromedriver.exe");
                string chromeDriverPath1 = Path.Combine(fileName);

                // 设置路径并添加浏览器配置环境
                var chromeDriver = new ChromeDriver(chromeDriverPath1, options);
                

                // 设置浏览器全屏显示
                chromeDriver.Manage().Window.Maximize();

                return CreateDriver(chromeDriver);
            }
            else
            {
                throw new NotSupportedException("不支持的操作系统");
            }
        }

        public static IWebDriver CreateDriver(IWebDriver driver)
        {
            // 可以在这里添加通用的设置，例如窗口大小、页面加载策略等
            return driver;
        }

        //结果解析，优先
        public static JObject FindVariableValue(ReadOnlyCollection<OpenQA.Selenium.LogEntry> logs, string variableName, bool isRequest)
        {
            foreach (var log in logs)
            {
                if (log.Message.Contains(variableName))
                {
                    string targetLog = log.Message;
                    if (isRequest)
                    {
                        var value = GetPassword(targetLog, variableName);
                        JObject result = new JObject();
                        result.Add(variableName, value);
                        return result;
                    }
                    else
                    {
                        // 在日志消息中直接搜索变量值
                        var value = FindVariableValue(targetLog, variableName);
                        JObject result = new JObject();
                        result.Add(variableName, value);
                        return result;
                    }
                }
            }
            // 返回对象名和空值
            JObject emptyResult = new JObject();
            emptyResult.Add(variableName, "");
            return emptyResult;
        }


        public static string GetPassword(string jsonStr, string variableName)
        {
            // 将 json 字符串解析为 JObject 对象
            JObject data = JObject.Parse(jsonStr);

            // 获取 postData 字段中的密码
            string password = data["message"]["params"]["request"]["postData"].ToString();

            // 将 postData 字符串解析为 JObject 对象，获取密码字段的值
            JObject passwordDict = JObject.Parse(password);
            return passwordDict[variableName].ToString();
        }

        public static JToken FindVariableValue(string logMessage, string variableName)
        {
            JObject jsonLog = JObject.Parse(logMessage);

            foreach (var property in jsonLog.Properties())
            {
                if (property.Name == variableName)
                {
                    return property.Value.ToString();
                }
                else if (property.Value.Type == JTokenType.Object)
                {
                    var subResult = FindVariableValue(property.Value.ToString(), variableName);
                    if (subResult != null) return subResult;
                }
            }
            return null;
        }




    }
}

